package com.lagou;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.List;
import java.util.Properties;

@SpringBootApplication
public class Application {

    static CuratorFramework zkClient;
    public static ConfigurableApplicationContext ac;

    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        zkClient = CuratorFrameworkFactory
                .builder()
                .namespace("base")
                .connectString("106.12.10.223:2181") //server地址
                .sessionTimeoutMs(5000) // 会话超时时间
                .connectionTimeoutMs(3000) // 连接超时时间
                .retryPolicy(retryPolicy) // 重试策略
                .build(); //
        zkClient.start();

        SpringApplication application = new SpringApplication(Application.class);


//        zkClient.create().forPath("/datasource/dbUrl","jdbc:mysql://localhost:3306/test?serverTimezone=UTC".getBytes());
//        zkClient.create().forPath("/datasource/dbusername","root".getBytes());
//        zkClient.create().forPath("/datasource/password","123456".getBytes());
//        zkClient.create().forPath("/datasource/driverClassName","com.mysql.jdbc.Driver".getBytes());
//          zkClient.create().forPath("/datasource/initialSize","3".getBytes());

        //从zookeeper读取配置
        List<String> children = zkClient.getChildren().forPath("/datasource");
        final Properties m = new Properties();
        for (String path : children) {
            byte[] datas = zkClient.getData().forPath("/datasource/" + path);
            m.put(path, new String(datas));
        }
        System.out.println(m);
        application.setDefaultProperties(m);

        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, "/datasource", true);

        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception {
                if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)) {
                    System.out.println("修改子节点:" + event.getData().getPath());
                    m.put(event.getData().getPath().replace("/datasource", ""), new String(event.getData().getData()));

                    DruidDataSource dc = (DruidDataSource) ac.getBean("myDatasource");
                    if (dc.isInited()) {
                        dc.restart();
                    }

                    if(event.getData().getPath().equals("/datasource/initialSize")) {
                        dc.setInitialSize(Integer.parseInt(new String(event.getData().getData())));
                    }
                    if(event.getData().getPath().equals("/datasource/dbusername")){
                        dc.setUsername(new String(event.getData().getData()));
                    }
                    if(event.getData().getPath().equals("/datasource/password")){
                        dc.setPassword(new String(event.getData().getData()));
                    }

                    if(event.getData().getPath().equals("/datasource/dbUrl")){
                        dc.setUrl(new String(event.getData().getData()));
                    }

                    dc.init();


                    System.out.println("修改配置后连接数："+dc.getInitialSize());

                }

            }
        });

        pathChildrenCache.start(PathChildrenCache.StartMode.NORMAL);
        ac = application.run();

        DruidDataSource dc = (DruidDataSource) ac.getBean("myDatasource");

        System.out.println("刚启动时连接数："+dc.getInitialSize());


    }


}
